﻿using System;
using Caliburn.Micro;
using DomusDotNet.Sbm.Client.WP7.ViewModels;
using DomusDotNet.Sbm.Client.WP7.Framework;
using System.Collections.Generic;

namespace DomusDotNet.Sbm.Client.WP7.ViewModels
{
    public class BusyState : PropertyChangedBase
    {
        int busyCount = 0;
		Stack<string> messages = new Stack<string>();
        object @lock = new object();
        public bool IsSet { get; private set; }
		public string Message { get; private set; }

		public BusyState() {
			messages.Push(string.Empty);
		}

		public IDisposable Set() {
			return Set(null);
		}
        public IDisposable Set(string message)
        {

            lock (@lock)
            {
                busyCount++;
				messages.Push(message);
            }

			Message = message;
            IsSet = true;
            return new DisposableAction(Reset);
        }
        public void Reset()
        {
            bool val;
            lock (@lock)
            {
                busyCount--;
                val = busyCount > 0;
				Message = messages.Pop();
            }

            IsSet = val;
        }
    }

    public interface IHasBusyState
    {
        BusyState BusyState { get; }
    }
}
